package com.example.aircraftwar2024.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.example.aircraftwar2024.ActivityManager;
import com.example.aircraftwar2024.R;
import com.example.aircraftwar2024.game.BaseGame;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {

    int musicState;
    final int MUSIC_ON=1;
    final int MUSIC_OFF=0;

    public static boolean connGameOverFlag;
    public static boolean single;
    public static boolean multi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        connGameOverFlag=true;  //默认单机游戏为true

        ActivityManager activityManager=ActivityManager.getActivityManager();
        activityManager.addActivity(this);

        Button btnStart=(Button) findViewById(R.id.btnStart);
        Button btnConn=(Button) findViewById(R.id.btnConn);

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                single = true;
                multi = false;
                Intent intent=new Intent(MainActivity.this, OfflineActivity.class);
                intent.putExtra("musicState",musicState);
                startActivity(intent);
            }
        });
        btnConn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                multi = true;
                single = false;
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("提示");
                builder.setMessage("匹配中，请等待");
                AlertDialog dialog = builder.create();
                dialog.show();

                connGameOverFlag=false;
                new Thread(new NetConn()).start();

            }
        });


        RadioGroup radioMusic = (RadioGroup) findViewById(R.id.radioMusic);
        radioMusic.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = (RadioButton) findViewById(checkedId);

                System.out.println(radioButton.getText());
                if(checkedId==R.id.btnMusicOn){
                    musicState=MUSIC_ON;
                }else {
                    musicState=MUSIC_OFF;
                }

            }
        });
    }


    protected class NetConn extends Thread{
        private Socket socket;
        private BufferedReader in;
        private PrintWriter writer;
        private Handler toClientHandler;
        private boolean send = false;

        private static  final String TAG = "MainActivity";

        public NetConn(){
        }

        @Override
        public void run(){
            try{
                socket = new Socket();
                socket.connect(new InetSocketAddress
                        ("10.0.2.2",9999),5000);
                //传入
                in = new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
                //传出
                writer = new PrintWriter(new BufferedWriter(
                        new OutputStreamWriter(
                                socket.getOutputStream(),"utf-8")),true);

                //接收服务器返回的数据
                Thread receiveServerMsg =  new Thread(){
                    @Override
                    public void run() {
                        String fromserver = null;
                        try {
                            while ((fromserver = in.readLine()) != null) {
                                System.out.println(fromserver);
                                //等待配对
                                if (fromserver.equals("waiting for match")) {
                                    System.out.println("hera");
                                }
                                //匹配成功
                                else if (fromserver.equals("matched")) {
                                    Intent intent = new Intent(MainActivity.this, OfflineActivity.class);
                                    intent.putExtra("musicState", musicState);
                                    startActivity(intent);
                                }
                                //返回对方分数值
                                //双方游戏均结束
                                else if (fromserver.equals("gameOver")) {
                                    connGameOverFlag = true;
                                } else if (fromserver.equals("bye")) {
                                    continue;
                                } else {
                                    int opponent_score = Integer.parseInt(fromserver);
                                    BaseGame.scoreEnemy = opponent_score;
                                }
                            }
                        }catch (IOException ex){
                            ex.printStackTrace();
                        }
                    }
                };
                receiveServerMsg.start();

                //Log.i(TAG,"connect to server");
                //writer.println("connect to server:im player");

                //客户端发送至服务器的数据
                Thread sendServerMsg =  new Thread(){
                    @Override
                    public void run(){
                        try {
                            while(!connGameOverFlag) {
                                Thread.sleep(1000);
                                //发送己方分数
                                writer.println(String.valueOf(BaseGame.score));
//                                System.out.println(BaseGame.gameOverFlag);
                                if(BaseGame.gameOverFlag&&send==false){
                                    writer.println("bye");
                                    send = true;
                                }
                            }
                            //联机游戏结束，跳转结束界面
                            Intent intent=new Intent(MainActivity.this, EndConnActivity.class);
                            startActivity(intent);

                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                };
                sendServerMsg.start();


            }catch(UnknownHostException ex){
                ex.printStackTrace();
            }catch(IOException ex){
                ex.printStackTrace();
            }
        }
    }
}